package com.pithypan.service.impl;


import com.pithypan.common.Constants;
import com.pithypan.common.ResponseCodeEnum;
import com.pithypan.common.ShareValidTypeEnums;
import com.pithypan.common.exceptionHandler.MyException;
import com.pithypan.common.utils.DateUtil;
import com.pithypan.common.utils.StringTools;
import com.pithypan.dto.SessionShareDto;
import com.pithypan.entity.FileShare;
import com.pithypan.mapper.FileShareMapper;
import com.pithypan.service.FileShareService;
import com.pithypan.vo.FileShareQuery;
import com.pithypan.vo.PaginationResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;

/**
 * 文件分享
 */
@Service
public class FileShareServiceImpl implements FileShareService {

    @Resource
    private FileShareMapper fileShareMapper;


    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public PaginationResultVo findListByPage(FileShareQuery query) {
        PaginationResultVo resultVo = new PaginationResultVo<>();
        resultVo.setPageSize(query.getPageSize());   //每页显示数
        resultVo.setPageNo(query.getPageNo());       //页码

        //计算总记录数
        Integer totalCount = this.fileShareMapper.findTotalCount(query);
        resultVo.setTotalCount(totalCount);

        //查询数据集
        int start = (query.getPageNo() - 1) * query.getPageSize();  //计算起始位置
        query.setStart(start);
        ArrayList<FileShare> list = this.fileShareMapper.findListByPage(query);
        resultVo.setList(list);

        //计算总页数
        int pageTotal = totalCount % query.getPageSize() == 0 ?
                totalCount /query.getPageSize() : (totalCount / query.getPageSize()) + 1;
        resultVo.setPageTotal(pageTotal);

        return resultVo;
    }


    /**
     * 添加分享文件
     * @param share
     */
    @Override
    public void saveShare(FileShare share) {
        ShareValidTypeEnums typeEnums = ShareValidTypeEnums.getByType(share.getValidType());
        if (typeEnums == null) {
            throw new MyException(ResponseCodeEnum.CODE_605.getCode(), ResponseCodeEnum.CODE_605.getMsg());
        }

        //如果文件有效期不是永久，则计算过期日期
        if (typeEnums != ShareValidTypeEnums.FOREVER) {
            share.setExpireTime(DateUtil.getAfterDate(typeEnums.getDays()));
        }

        //如果前端没有指定提取码，则由系统自动生成
        if (StringTools.isEmpty(share.getCode())) {
            share.setCode(StringTools.getRandomString(Constants.LENGTH_5));
        }

        Date curDate = new Date();
        share.setShareTime(curDate);                              //设置分享时间
        share.setShowCount(0);                                    //设置浏览次数
        share.setShareId(StringTools.getRandomString(20));  //设置id

        this.fileShareMapper.insert(share);
    }


    /**
     * 删除分享文件
     * @param shareIdArray
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFileShareBatch(String[] shareIdArray, String userId) {
        Integer count = this.fileShareMapper.deleteFileShareBatch(shareIdArray, userId);
        if (count != shareIdArray.length) {
            throw new MyException(ResponseCodeEnum.CODE_605.getCode(), ResponseCodeEnum.CODE_605.getMsg());
        }
    }


    /**
     * 根据shareId获取
     * @param shareId
     * @return
     */
    @Override
    public FileShare getFileShareByShareId(String shareId) {
        return this.fileShareMapper.findFileShareByShareId(shareId);
    }


    /**
     * 校验提取码，并提取分享文件
     * @param shareId
     * @param code 前端用户输入的提取码
     * @return
     */
    @Override
    public SessionShareDto checkShareCode(String shareId, String code) {
        FileShare share = this.fileShareMapper.findFileShareByShareId(shareId);
        //判断分享文件是否不存在，或已过期
        if (share == null || (share.getExpireTime() != null && new Date().after(share.getExpireTime()))) {
            throw new MyException(ResponseCodeEnum.CODE_902.getCode(), ResponseCodeEnum.CODE_902.getMsg());
        }

        //校验提取码
        if (!share.getCode().equals(code)) {
            throw new MyException(ResponseCodeEnum.CODE_903.getCode(), ResponseCodeEnum.CODE_903.getMsg());
        }

        //更新浏览次数 + 1
        this.fileShareMapper.updateShareShowCount(shareId);
        SessionShareDto sessionShareDto = new SessionShareDto();
        sessionShareDto.setShareId(shareId);
        sessionShareDto.setFileId(share.getFileId());
        sessionShareDto.setShareUserId(share.getUserId());
        sessionShareDto.setExpireTime(share.getExpireTime());
        return sessionShareDto;
    }
}
